// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const username = event.username
  const avatarUrl = event.avatarUrl
  const usersDb = cloud.database().collection('users')

  const { data } = await usersDb.where({
    openid
  }).get()

  // 如果没有相关数据就注册
  if (data.length === 0) {
    const lengthObj = await usersDb.count()
    const data = {
      openid,
      username,
      avatarUrl,
      _id: lengthObj.total + 1,
      groups: [],
      books: [],
      keepTime: 7,
      status: 0,
      permission: true,
      bookCount: 0,
      comments: []
    }
    usersDb.add({
      data
    })
    return {
      fresh: true,
      userInfo: data
    }
  } else {
    return {
      fresh: false,
      userInfo: data[0]
    }
  }
}